// pages/search/search.js
import request from '../../utils/request';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent: '', // 搜索框placeholder
    hotList: [], // 热搜榜数据
    searchContent: '', // 搜索内容
    searchList: [], // 搜索结果
    historyList: [] // 搜索历史
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getInitData();
    // 设置搜索防抖
    this.getSearchDebounce = this.debounce(this.getSearchResponse, 500);
    // 读取本地搜索历史记录
    let historyList = wx.getStorageSync('historyList');
    this.setData({
      historyList: historyList ? historyList : []
    });
  },

  // 获取初始化数据
  async getInitData() {
    let placeholderData = await request('search/default'); // placeholder内容
    let hotListData = await request('search/hot/detail'); // 热词内容
    // console.log(placeholderData);
    // console.log(hotListData);
    this.setData({
      placeholderContent: placeholderData.data.showKeyword,
      hotList: hotListData.data
    });
  },

  // input输入框值改变时的回调
  handleInput(e) {
    // console.log(e);
    this.setData({
      searchContent: e.detail.value.trim()
    });
    this.getSearchDebounce();
  },

  // 节流debounce代码（定时器）：
  debounce(fn, delay) {
    let timeout = null;
    return () => {
      (timeout !== null && clearTimeout(timeout)) || (timeout = setTimeout(fn, delay));
    };
  },

  // 请求搜索结果
  async getSearchResponse() {
    // console.log('keywords: ', this.data.searchContent);
    let {
      searchContent,
      historyList
    } = this.data;
    if (!searchContent) {
      this.setData({
        searchList: []
      });
      return;
    }
    // 获取搜索结果
    let serachData = await request('search', {
      keywords: searchContent,
      limit: 10
    });

    if (historyList.indexOf(searchContent) !== -1) {
      historyList.splice(historyList.indexOf(searchContent), 1);
    }
    historyList.unshift(searchContent);
    wx.setStorageSync('historyList', historyList);

    // 保存搜索关键字
    this.setData({
      searchList: serachData.result.songs,
      historyList
    });
  },

  // 清空搜索内容
  clearSearchContent() {
    this.setData({
      searchContent: '',
      searchList: []
    });
  },

  // 删除搜索历史记录
  deleteSearchHistory() {
    wx.showModal({
      content: '确定删除记录吗？',
      success: e => {
        if (e.confirm) {
          // 清空data中的historyList
          this.setData({
            historyList: []
          })
          // 清空storage中的historyList
          wx.removeStorageSync('historyList')
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});